package com.centanet.framework.task;

import android.os.AsyncTask;

import com.centanet.framework.interfaces.IDownloadResult;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 下载任务
 */
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {

    private final static String TAG = "DownloadTask";

    private final OkHttpClient okHttpClient;
    private final String url;
    private final File file;
    private final IDownloadResult downloadResult;

    /**
     * @param okHttpClient   {@link OkHttpClient}
     * @param url            下载地址
     * @param file           保存的文件
     * @param downloadResult 下载结果回调
     */
    public DownloadTask(OkHttpClient okHttpClient, String url, File file, IDownloadResult downloadResult) {
        this.okHttpClient = okHttpClient;
        this.url = url;
        this.file = file;
        this.downloadResult = downloadResult;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Logger.t(TAG).d("Download start url : %s", url);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            InputStream is = null;
            byte[] buf = new byte[1024];
            int len;
            FileOutputStream fos = null;
            try {
                is = response.body().byteStream();
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        Logger.t(TAG).d("Download end url : %s", url);
        Logger.t(TAG).d("Download end result : " + aBoolean);
        downloadResult.result(!aBoolean);
    }
}
